package com.ray.auth.system.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.flyong.cache.query.cache.CacheConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ray.auth.common.CommonValue;
import com.ray.auth.system.emun.ManagerType;
import com.ray.auth.system.emun.UseStatus;
import com.ray.auth.system.emun.UserType;
import com.ray.auth.system.service.OrganizationService;
import com.ray.auth.system.service.UserService;
import com.ray.auth.system.table.customMapper.CustomUserMapper;
import com.ray.auth.system.table.entity.Organization;
import com.ray.auth.system.table.entity.User;
import com.ray.auth.system.table.entity.UserExample;
import com.ray.auth.system.table.entity.UserExample.Criteria;
import com.ray.auth.system.table.mapper.UserMapper;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.zjhc.flyhong.common.function.enums.DeleteEnum;
import com.zjhc.flyhong.common.function.exception.BussinessException;
import com.zjhc.flyhong.common.function.operator.LoginUser;
import com.zjhc.flyhong.common.function.operator.PageDto;
import com.zjhc.flyhong.common.function.validate.EntityValidate;
import com.zjhc.flyhong.common.function.validate.rule.FieldRule;
import com.zjhc.flyhong.common.function.validate.rule.RuleEnum;
import com.zjhc.flyhong.common.util.Md5Util;
import com.zjhc.flyhong.common.util.UUIDUtil;
import com.zjhc.flyhong.common.web.ErrorMsg;
import com.zjhc.flyhong.common.web.Result;
import com.zjhc.flyhong.common.web.ResultHelper;
import com.zjhc.flyhong.common.web.SuccessMsg;
import com.zjhc.flyhong.common.web.base.BaseService;
/**
 * <h1>系统权限应用  用户  服务实现</h1>
 * @创建人 ray
 * @创建时间 2017-06-13
 * @版本 1.0
 * @重要修改备注 
 * 
 */
@Service
public class UserServiceImpl extends BaseService implements UserService {
	/**************实现类  其他对象 引用  开始***********************/
	/**日志对象**/
	private static Logger logger = Logger.getLogger(UserServiceImpl.class);
	/**应用数据库操作对象**/
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private CustomUserMapper customUserMapper;
	@Autowired
	private OrganizationService organizationService;
	
	
	/**************实现类  其他对象 引用  结束***********************/
	/***
	 * @描述 <h1>获取用户</h1><br/>
	 * @参数 entity 菜单对象
	 * @返回 result  返回结果  result.status => 0表示成功 ,其余表示失败
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public User queryUser(String loginName) {
		FieldRule fieldRule = new FieldRule();
		fieldRule.addObjectIsNotNull("登录名");
	    Result<Object> result =	EntityValidate.validate(loginName, fieldRule);
	    if(!result.codeSuccess()){
	    	return null;
	    }
		//设置查询条件
		UserExample example = new UserExample();
		example.createCriteria().andLoginNameEqualTo(loginName)
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());//使用中的数据
        //获取查询信息
		List<User> userList = userMapper.selectByExample(example);
		//没有查询到结果的时候 
		if(ObjectUtil.isNull(userList) || userList.isEmpty()){
			return null;
		}
		//查询到多条语句 异常
		if(userList.size() > 1){
			throw new RuntimeException("two many record by query,RecordCount:"+userList.size());
		}
		return userList.get(0);
	}
	
	/***
	 * @描述 <h1>获取用户</h1><br/>
	 * @参数 userId 用户id
	 * @返回 user
	 */
	@CacheConfig(key="user",paramsSize=1,query=true,expire=1800)
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public User queryUserByUserId(String userId) {
		//对象验证
		FieldRule fieldRule = new FieldRule();
		fieldRule.addObjectIsNotNull("用户编号");
	    Result<Object> result =	EntityValidate.validate(userId, fieldRule);
	    if(!result.codeSuccess()){
	    	logger.error(result.getMsg());
	    	return null;
	    }
		//设置查询条件
		UserExample example = new UserExample();
		example.createCriteria().andUserIdEqualTo(userId)
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());//使用中的数据
        //获取查询信息
		List<User> userList = userMapper.selectByExample(example);
		//没有查询到结果的时候 
		if(ObjectUtil.isNull(userList) || userList.isEmpty()){
			return null;
		}
		//查询到多条语句 异常
		if(userList.size() > 1){
			throw new RuntimeException("two many record by query,RecordCount:"+userList.size());
		}
		return userList.get(0);
	}
	
	
	/**
	 * 新增用户
	 * @param params 用户对象
	 * @param loginUser 登录用户
	 * @return
	 */
	@Transactional
	public Result<Object> addUser(User params, LoginUser loginUser){
		//对象验证 
		/*****************验证开始************************/	
		FieldRule fieldRule = new FieldRule();
		fieldRule.addRule(RuleEnum.IS_NOT_NULL, String.class, "userName","用户名");
		Result<Object> rs =	EntityValidate.validate(params, fieldRule);
		if(!rs.codeSuccess())return rs;
		//判断是否存在
		Result<Object> result = userExist(params);
		if(!result.codeSuccess()) return result;
		/******************验证结束*******************/
		//超级管理远添加用户 用户的租户根据组织获取
		if(loginUser.isSuperManager()){
			Organization org = organizationService.queryOrgByOrgCode(params.getOrgCode());
			params.setTenantId(org.getTenantId());
		}else{
			params.setTenantId(loginUser.getTenantId());
		}
		params.setUserId(UUIDUtil.getUUID());
		params.setIsDelete(DeleteEnum.USE.getValue());
		params.setManagerType(ManagerType.REMBER.getType());
		params.setPassword(Md5Util.getMd5(CommonValue.PassWord));
		this.setUserForAdd(params, loginUser);
		//执行成功数量	
		int exeCount = userMapper.insertSelective(params);
		if(exeCount != 1)return ResultHelper.getError();
		return ResultHelper.getSuccess();
	}
	
	/**
	 * 判断用户是否存在
	 * @param params
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	private Result<Object> userExist(User params) {
		Result<Object> result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		User user = queryUser(params.getLoginName());
		//判断
		if(ObjectUtil.isNotNull(user)){
			if(!StrUtil.equals(user.getUserId(), params.getUserId())){
				result = new Result<Object>(1,CommonValue.LoginNameExist);
			}
		}
		return result;
	}

	/**
	 * 查询用户
	 * @param id 用户ID
	 * @param user
	 * @return
	 */
	@CacheConfig(key="user",paramsSize=1,query=true,expire=1800)
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public User queryUser(String id, LoginUser user){
		return userMapper.selectByPrimaryKey(id);
	}
	/**
	 * 更新用户信息
	 * @param params 用户信息
	 * @param loginUser
	 * @return
	 */
	@CacheConfig(key="user",paramsSize=1,update=true,id="userId",clearKey="userList")
	@Transactional
	public Result<Object> updateUser(User params, LoginUser loginUser){
		//判断是否存在
		Result<Object> result = userExist(params);
		if(!result.codeSuccess()) return result;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		this.setUserForUpdate(params, loginUser);
		int opCount = userMapper.updateByPrimaryKeySelective(params);
		if(opCount != 1){
			logger.error("UserServiceImpl=>updateUser is error");
			throw new BussinessException(-1, ErrorMsg.UPDATE_ERROR);
		}
		return result;
	}
	/**
	 * 删除用户
	 * @param id
	 * @param loginUser
	 * @return
	 */
	@CacheConfig(key="user",paramsSize=1,delete=true,clearKey="userList")
	@Transactional
	public Result<Object> deleteUser(String id, LoginUser loginUser){
		//校验
		FieldRule fieldRule = new FieldRule();
		fieldRule.addObjectIsNotNull("用户编号");
		Result<Object> rs =	EntityValidate.validate(id, fieldRule);
		if(!rs.codeSuccess())return rs;
		
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		User record = new User();
		record.setUserId(id);
		record.setIsDelete(DeleteEnum.DELETE.getValue());
		this.setUserForUpdate(record, loginUser);
		int opCount = userMapper.updateByPrimaryKeySelective(record);
		if(opCount != 1){
			logger.error("UserServiceImpl=>deleteUser is error");
			throw new BussinessException(-1, ErrorMsg.DELETE_ERROR);
		}
		return result;
	}
	/**
	 * 分页查询用户
	 * @param params
	 * @param page
	 * @param loginUser
	 * @return
	 */
	@CacheConfig(key="userList",expire=60,paramsSize=2,query=true)
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public PageDto<User> queryUserList(User params, PageDto<User> page, LoginUser loginUser){
		UserExample example = new UserExample();
		Criteria criteria =  example.createCriteria();
		//超级管理员能看到全部数据
		if(!loginUser.isSuperManager()){
			criteria.andTenantIdEqualTo(loginUser.getTenantId());
		}
		//部门过滤
		if(StrUtil.isNotBlank(params.getOrgCode())){
			criteria.andOrgCodeEqualTo(params.getOrgCode());
		}
		//用户模糊查询
		if(StrUtil.isNotBlank(params.getUserName())){
			criteria.andUserNameLike(params.getUserName()+"%");
		}
		//登录名模糊查询
		if(StrUtil.isNotBlank(params.getLoginName())){
			criteria.andLoginNameLike(params.getLoginName()+"%");
		}
		criteria.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		criteria.andPasswordIsNotNull();
		this.setExamplePage(example, page);
		page.setTotal(userMapper.countByExample(example));
		page.setRecords(userMapper.selectByExample(example));
		return page;
	}
	
	/**
	 * 新增系统管理员
	 * @param params 用户对象
	 * @param loginUser 登录用户
	 * @return
	 */
	@Transactional
	public Result<Object> addManagerUser(String id, LoginUser loginUser){
		//校验
		FieldRule fieldRule = new FieldRule();
		fieldRule.addObjectIsNotNull("用户编号");
		Result<Object> rs =	EntityValidate.validate(id, fieldRule);
		if(!rs.codeSuccess())return rs;
		
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		User params = new User();
		params.setUserId(id);
		params.setManagerType(ManagerType.SUPER.getType());
		this.setUserForUpdate(params, loginUser);
		int opCount = userMapper.updateByPrimaryKeySelective(params);
		if(opCount != 1){
			logger.error("UserServiceImpl=>updateUser is error");
			throw new BussinessException(-1, ErrorMsg.UPDATE_ERROR);
		}
		return result;
	}
	/**
	 * 取消系统管理员系统管理员
	 * @param params 用户对象
	 * @param loginUser 登录用户
	 * @return
	 */
	@Transactional
	public Result<Object> cancelManagerUser(String id, LoginUser loginUser){
		//校验
		FieldRule fieldRule = new FieldRule();
		fieldRule.addObjectIsNotNull("用户编号");
		Result<Object> rs =	EntityValidate.validate(id, fieldRule);
		if(!rs.codeSuccess())return rs;
		
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		User params = new User();
		params.setUserId(id);
		params.setManagerType(ManagerType.REMBER.getType());
		this.setUserForUpdate(params, loginUser);
		int opCount = userMapper.updateByPrimaryKeySelective(params);
		if(opCount != 1){
			logger.error("UserServiceImpl=>updateUser is error");
			throw new BussinessException(-1, ErrorMsg.UPDATE_ERROR);
		}
		return result;
	}
	/**
	 * 重置密码
	 * @param params 用户对象
	 * @param loginUser 登录用户
	 * @return
	 */
	@Transactional
	public Result<Object> resetPassword(String id, LoginUser loginUser){
		FieldRule fieldRule = new FieldRule();
		fieldRule.addObjectIsNotNull("用户编号");
		Result<Object> rs =	EntityValidate.validate(id, fieldRule);
		if(!rs.codeSuccess())return rs;
		
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		User params = new User();
		params.setUserId(id);
		params.setPassword(Md5Util.getMd5(CommonValue.PassWord));
		this.setUserForUpdate(params, loginUser);
		int opCount = userMapper.updateByPrimaryKeySelective(params);
		if(opCount != 1){
			logger.error("UserServiceImpl=>updateUser is error");
			throw new BussinessException(-1, ErrorMsg.UPDATE_ERROR);
		}
		return result;
	}
	
	/**
	 * 新增接口用户
	 * @param params 用户对象
	 * @param loginUser 登录用户
	 * @return
	 */
	@Transactional
	public Result<Object> addInterfaceUser(User params, LoginUser loginUser){
		//对象验证 
		/*****************验证开始************************/	
		FieldRule fieldRule = new FieldRule();
		fieldRule.addRule(RuleEnum.IS_NOT_NULL, String.class, "userName","用户名");
		Result<Object> rs =	EntityValidate.validate(params, fieldRule);
		if(!rs.codeSuccess())return rs;
		//判断是否存在
		Result<Object> result = userExist(params);
		if(!result.codeSuccess()) return result;
		params.setUserId(UUIDUtil.getUUID());
		params.setIsDelete(DeleteEnum.USE.getValue());
		params.setManagerType(ManagerType.REMBER.getType());
		//超级管理远添加用户 用户的租户根据组织获取
		if(loginUser.isSuperManager()){
			Organization org = organizationService.queryOrgByOrgCode(params.getOrgCode());
			params.setTenantId(org.getTenantId());
		}else{
			params.setTenantId(loginUser.getTenantId());
		}
		this.setUserForAdd(params, loginUser);
		//执行成功数量	
		int exeCount = userMapper.insertSelective(params);
		if(exeCount != 1)return ResultHelper.getError();
		return ResultHelper.getSuccess();
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public LoginUser getInerfaceUser(String userName) {
		LoginUser loginUser =  null;
		// 获取用户信息
		User user = this.queryUser(userName);
		if (ObjectUtil.isNotNull(user)) {
			loginUser = new LoginUser();
			loginUser.setExtendUser(user);
			loginUser.setUserName(user.getUserName());
			loginUser.setLoginName(userName);
			loginUser.setUserId(user.getUserId());
			//超级管理员
			if(StrUtil.equals(user.getManagerType(), ManagerType.SUPER.getType())){
				loginUser.setSuperManager(true);
			}
			//超级管理员
			if(StrUtil.equals(user.getUserType(), UserType.MANAGER.getType())){
				loginUser.setManager(true);
			}
			
			// 获取部门信息
			Organization dept = organizationService.queryOrgByOrgCode(user.getOrgCode());
			if (ObjectUtil.isNotNull(dept)) {
				loginUser.setDeptCode(dept.getOrgId());
				loginUser.setDeptName(dept.getOrgName());
			}
			// 获取所属组织信息
			Organization org = organizationService.queryOrgByTenantId(user.getTenantId());
			if (ObjectUtil.isNotNull(org)) {
				loginUser.setOrgCode(org.getOrgId());
				loginUser.setOrgName(org.getOrgName());
				loginUser.setTenantId(org.getTenantId());
			}
		}
		
		return loginUser;
	}

	@Transactional
	public Result<Object> updatePassword(User params, String hisPassword, LoginUser loginUser) {
		/*****************验证开始************************/	
		FieldRule fieldRule = new FieldRule();
		fieldRule.addRule(RuleEnum.IS_NOT_NULL, String.class, "password","新密码");
		Result<Object> rs =	EntityValidate.validate(params, fieldRule);
		if(!rs.codeSuccess())return rs;
		Result<Object> result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		this.setUserForUpdate(params, loginUser);
		//设置加密密码
		params.setPassword(Md5Util.getMd5(params.getPassword()));
		UserExample example = new UserExample();
		example.createCriteria().andUserIdEqualTo(params.getUserId())
		.andPasswordEqualTo(Md5Util.getMd5(hisPassword))
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		int opCount = userMapper.updateByExampleSelective(params, example);
		if(opCount != 1){
			logger.error("UserServiceImpl=>updatePassword is error");
			throw new BussinessException(-1, ErrorMsg.UPDATE_ERROR);
		}
		return result;
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public User queryAdminUser() {
		//设置查询条件
		UserExample example = new UserExample();
		example.createCriteria()
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());//使用中的数据
        //获取查询信息
		List<User> userList = userMapper.selectByExample(example);
		//没有查询到结果的时候 
		if(ObjectUtil.isNull(userList) || userList.isEmpty()){
			return null;
		}
		//查询到多条语句 异常
		/*if(userList.size() > 1){
			throw new RuntimeException("two many record by query,RecordCount:"+userList.size());
		}*/
		return userList.get(0);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<User> queryUser(List<String> ids) {
		UserExample example = new UserExample();
		example.createCriteria().andUserIdIn(ids);
		return userMapper.selectByExample(example);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<User> queryUserList(List<String> userIds, List<String> roleIds, LoginUser user) {
        UserExample example = new UserExample();
        Criteria criteria =  example.createCriteria();
        criteria.andIsDeleteEqualTo(DeleteEnum.USE.getValue()).andUserStatusEqualTo(UseStatus.ON.getType());
        if(!user.isSuperManager()){
        	criteria.andTenantIdEqualTo(user.getTenantId());
        }
		return customUserMapper.selectUserList(userIds, roleIds, example);
	}
	
	
}
